#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#include <windows.h>

#define NC "\e[0m"
#define RED "\e[0;31m"
#define GRN "\e[0;32m"
#define CYN "\e[0;36m"
#define REDB "\e[41m"

using namespace std;
using namespace filesystem;

bool fileCopy(string_view oriFile, string_view targetFile)
{
   
    ifstream read(oriFile.data(), ios_base::in | ios_base::binary);
    ofstream out(targetFile.data(), ios_base::out | ios_base::binary);

    if (!read)
    {
        std::cout <<"Failed to find file : " << oriFile << '\n';
        return false;
    }
    out << read.rdbuf();
    cout << targetFile << " 文件替换成功！" << endl;
    return true;
}

bool foundAndReplace(string_view fn, string_view rootDir)
{
    filesystem::path root{rootDir};

    if (!exists(root))
    {
        return NULL;
    }

    recursive_directory_iterator begin{root};
    recursive_directory_iterator end{};
    // std::vector<string> result ;
    // result.reserve(10);
    bool found = false;
    cout << GRN "开始搜索...."<<endl;
    for (auto iter{begin}; iter != end; ++iter)
    {

        auto &entry = *iter; // Dereference iter to access directory_entry.

        if (is_regular_file(entry))
        {
            const string tar = entry.path().string();
            cout<<tar<<endl;
            if (tar.find(fn) != string::npos) // 找到需要替换的文件
            {
                cout << "找到目标文件: " << tar << endl;
                cout << "是否进行替换（Yes/No） :";
                char input[10];
                cin >> input;
                if ('Y' == toupper(*input))
                {
                    fileCopy(fn, tar);
                }
                // result.push_back(tar);
                found = true;
                break;
            }
        }
        else if (is_directory(entry))
        {
        }
    }

    if (!found)
    {
        cout << RED "未找到对应替换文件，需要手动添加" << endl;
    }
    cout << NC;
}

int main(int argc, char **argv)
{
    SetConsoleOutputCP(65001);
    cout <<GRN;
    cout <<  "argc : " << argc << endl;

    const string  rootdir = "Y:\\temp\\CustomisationSP5\\PMLLIB\\CMIH\\AMA";
    if (argc > 1)
    {
        for (size_t i = 1; i < argc; i++)
        {
            string fileName = *argv++;

            foundAndReplace(fileName,rootdir);
        }
    }
}